package com.w4cms.interceptor;

import org.apache.log4j.Logger;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.w4cms.core.Consts;
import com.w4cms.model.SysMenu;
import com.w4cms.model.SysUser;
import com.w4cms.utils.RightsUtils;
import com.w4cms.utils.Tools;
/**
 *  后台管理员权限管理
 *  @author wch (185656156@qq.com)
 *  @version V0.0.1  2014-4-10
 *  <table style="border:1px solid gray;;text-align:center">
 *          <tr>
 *          <th width="100px">版本号</th>
 *          <th width="100px">动作</th>
 *          <th width="100px">修改人</th>
 *          <th width="100px">修改时间</th>
 *          </tr>
 *          <!-- 以 Table 方式书写修改历史 -->
 *          <tr>
 *          <td>0.0.0</td>
 *          <td>创建类</td>
 *          <td>wch</td>
 *          <td>2014-4-10 下午2:34:08</td>
 *          </tr>
 *    </table>
 */
public class AdminInterceptor implements Interceptor{
	private Logger logger = Logger.getLogger(AdminInterceptor.class);
	public void intercept(ActionInvocation ai) {
		Controller c = ai.getController();
		SysUser user = c.getSessionAttr(Consts.SESSION_USER);
		String contextPath = c.getRequest().getContextPath();
		String servletPath = c.getRequest().getServletPath();
		if(user==null){
			c.redirect(contextPath + "/admin/login.html");
			return;
		}
		if(servletPath.matches(Consts.NO_INTERCEPTOR_PATH) || "admin".equals(user.getStr("username")))
		{
			ai.invoke();
			return;
		}else{
			Integer menuId = null;
			if(Consts.SESSION_MENUS==null){
				Consts.SESSION_MENUS = SysMenu.dao.find("select * from sys_menu");
			}
			for(SysMenu m : Consts.SESSION_MENUS){
				String menuUrl = m.getStr("url");
				if(Tools.notEmpty(menuUrl)){
					if(servletPath.contains(menuUrl)){
						menuId = m.getInt("id");
						break;
					}else{
						String[] arr = menuUrl.split("\\.");
						String regex = "";
						if(arr.length==2){
							regex = "/?"+arr[0]+"(/.*)?."+arr[1];
							
						}else{
							regex = "/?"+menuUrl+"(/.*)?.html";
						}
						if(servletPath.matches(regex)){
							menuId = m.getInt("id");
							break;
						}
					}
				}
			}
			if(menuId!=null){
				String userRights = c.getSessionAttr(Consts.SESSION_USER_RIGHTS);
				String roleRights = c.getSessionAttr(Consts.SESSION_ROLE_RIGHTS);
				if(RightsUtils.testRights(userRights, menuId) || RightsUtils.testRights(roleRights, menuId)){
					ai.invoke();
					return;
				}else{
					logger.info("用户:"+user.getStr("username")+" 试图访问"+servletPath+"被阻止!");
					c.renderError(403);
					return;
				}
			}
			ai.invoke();
		}
	}

}
